package cn.chainco.cts.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;

import cn.chainco.cts.iservice.CommonManager;
import cn.chainco.cts.iservice.ImManager;
import cn.chainco.cts.jdo.IM;
import cn.chainco.cts.jdo.User;
import cn.chainco.cts.jdo.Verification;
import cn.chainco.cts.jdo.Work;
import cn.chainco.cts.utils.CookieUtil;
import cn.chainco.cts.utils.TimeUtil;
import cn.chainco.cts.utils.query.Page;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings({ "unchecked" })
@InterceptorRef("ctsInterceptors")
public class ImAction extends ActionSupport{
	private static final long serialVersionUID = 4240950578650201534L;
	
	private ImManager imManager;
	private CommonManager commonManager;
	private IM im;
	private List<IM> imList;
	private Map<User, Integer> imMap;
	private Long uid; // 聊天对象的id
	private long workId; // 关联单id
	private String msgContent;// 发送内容
	private List<Map<User, Integer>> dataList;
	private Page pager;
	private int pageSizeIm;
	private int pageNumberIm;
	
public static Map<Long, Long> userLastActiveMap; //用于保存用户最后一次向服务器发送响应时间
	
	static{
		userLastActiveMap = Collections.synchronizedMap(new HashMap<Long, Long>(160));
	}
	
	public static boolean isUserOnline(long userId){
		long lastActiveTime = userLastActiveMap.containsKey(userId) ? userLastActiveMap.get(userId) : 0L;
		long nowTime = System.currentTimeMillis();
		int timeOutSecond = 60; //60秒为用户不在线超时时间
		return (nowTime - lastActiveTime) <= timeOutSecond * 1000 ? true : false;
	}

	// 检查用户是否在线
	@Action("checkUserActive")
	public void checkUserActive(){
		int code = 0;
		try{
			long userId = Long.parseLong(CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_userid"));
			userLastActiveMap.put(userId, System.currentTimeMillis());
		}catch(Exception e){
			code = 1;
		}
		outputData(code);
	}
	
	
	@Action("toListIm")//打开聊天窗口
	public String toListIm(){
		HttpServletRequest request=ServletActionContext.getRequest();
		long userId = Long.parseLong(CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_userid"));
		User user = this.commonManager.findEntityByPK(User.class, userId);
		
		String imContent = "";
		String imAboutTopic_url = "";
		String imAboutTopic_content = "";
		if(uid == null){
			uid = 0l;
		}
		User sender = this.commonManager.findEntityByPK(User.class, uid);
		if(sender!=null){
			imList = imManager.getNotReadChatByOneUser(user, sender);
			imManager.modifyIMsReadState(imList);// 修改未读状态
			if(imList != null && imList.size() != 0){
				for(IM im: imList){
					if(im.getWorkId() != null){
						Work w = this.commonManager.findEntityByPK(Work.class, im.getWorkId());
						if(w != null){
							im.setSheetUrl("window.open('workDetail.action?id="+w.getId()+"')");
						}else{
							im.setSheetUrl("alert('该价格单已被删除！')");
						}
						imAboutTopic_url = im.getSheetUrl();
						imAboutTopic_content = im.getMsgContent();
					}else{
						imContent += sender.getUserName() + "　" + TimeUtil.getFormatTimeString(im.getSendDate()) + "\r\n　　" + im.getMsgContent() + "\r\n";
					}
				}
			}
		}
		request.setAttribute("imAboutTopic_url", imAboutTopic_url);
		request.setAttribute("imAboutTopic_content", imAboutTopic_content);
		request.setAttribute("imContent", imContent);
		request.setAttribute("sender", sender);
		String aboutSheet = request.getParameter("aboutSheet");
		request.setAttribute("aboutSheet", aboutSheet);
		
		request.setAttribute("heName", "xxx@xx");
		return "im/im";
	}
	
	@Action("checkMsg") //扫描信息
	public String checkMsg(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String userIdStr = CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_userid");
		if(userIdStr != null && !"".equals(userIdStr)){
			long userId = Long.parseLong(CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_userid"));
			User user = this.commonManager.findEntityByPK(User.class, userId);
			//最近联系人列表
			List<User> userList = imManager.getNearIMByUser(user);
			userList.remove(user);
			int totalCount = 0;
			dataList = imManager.getListNotReadInfoGroupByUser(user);
			totalCount = dataList.size();
			if(totalCount == 0){
				for(User u: userList){
					Map<User, Integer> m = new HashMap<User, Integer>();
					m.put(u, 0);
					dataList.add(m);
				}
			}else{
				List<Map<User, Integer>> listTemp = new ArrayList<Map<User, Integer>>();
				List<Long> uList = new ArrayList<Long>();
				for(Map<User, Integer> map: dataList){
					for(User u: map.keySet()){
						uList.add(u.getId());
					}
				}
				for(User u: userList){
					try{
						if(u==null || u.getId()==0){
							continue;
						}
					}catch (Exception e) {
						continue;
					}
					if(!uList.contains(u.getId())){
						Map<User, Integer> m = new HashMap<User, Integer>();
						m.put(u, 0);
						listTemp.add(m);
					}
				}
				for(Map<User, Integer> map: listTemp){
					dataList.add(map);
				}
			}
			request.setAttribute("totalCount", totalCount);
		}
		return "im/imTip";
	}
	
	@Action("sendMsg")// 发送信息
	public void sendMsg(){
		HttpServletRequest request = ServletActionContext.getRequest();
		long userId = Long.parseLong(CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_userid"));
		User sender = this.commonManager.findEntityByPK(User.class, userId); // 发送人是登录人
		User receiver = this.commonManager.findEntityByPK(User.class, uid);
		
		if(workId != 0){
			Work w = this.commonManager.findEntityByPK(Work.class, workId);
			String aboutSheet = request.getParameter("aboutSheet");
			// 说明从单进来的
			if("1".equals(aboutSheet)){
				String perSheet = "关于您的订单"+ "#" + w.getId() + "#";
				IM im = new IM();
				im.setMsgContent(perSheet);
				im.setReceiver(receiver);
				im.setSender(sender);
				im.setSendDate(new Date());
				im.setWorkId(w.getId());
				this.commonManager.saveEntity(im);
			}
		}
		
		im = new IM();
		im.setReceiver(receiver);
		im.setSender(sender);
		im.setSendDate(new Date());
		im.setMsgContent(msgContent);

		this.commonManager.saveEntity(im);
		outputData(sender.getUserName() + "　" + TimeUtil.getFormatTimeString(im.getSendDate()) + "\r\n　　" + im.getMsgContent() + "\r\n");
	}
	
	@Action("getImContentHistory")// 获取历史内容
	public String getImContentHistory(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String searchContent = request.getParameter("searchContent");
		if("undefined".equals(searchContent)){
			searchContent = "";
		}
		long userId = Long.parseLong(CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_userid"));
		User user = this.commonManager.findEntityByPK(User.class, userId);

		User sender = this.commonManager.findEntityByPK(User.class, uid);
		List<IM> imList2 = imManager.getChatHistory(user, sender, searchContent);

		for(IM im: imList2){
			if(im.getWorkId() != null){
				Work w = this.commonManager.findEntityByPK(Work.class, im.getWorkId());
				if(w != null){
					im.setSheetUrl("window.open('workDetail.action?id="+w.getId()+"')");
				}else{
					im.setSheetUrl("alert('该订单已被删除！')");
				}
			}
		}

		if(pageSizeIm == 0)
			pageSizeIm = 5;
		if(pageNumberIm == 0)
			pageNumberIm = 1;
		pager = new Page();
		pager.setElements(imList2);
		pager.setPageNumber(pageNumberIm);
		pager.setPageSize(pageSizeIm);
		pager.setTotalElements(imList2.size());
		imList = pager.getCurrentElements();

		request.setAttribute("pageCount", pager.getLastPageNumber());
		request.setAttribute("searchContent", searchContent);
		return "im/imHistory";
	}
	
	@Action("delImContentHistory")//	 清空历史记录
	public void delImContentHistory(){
		try{
			long userId = Long.parseLong(CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_userid"));
			User user1 = this.commonManager.findEntityByPK(User.class, userId); // 登录者
			User user2 = this.commonManager.findEntityByPK(User.class, uid);
			IM newIm = imManager.getNewChat(user1, user2);
			if(newIm.getDeleterId() != null && !"".equals(newIm.getDeleterId())){
				newIm.setDeleterId(newIm.getDeleterId() + "," + user1.getId());
			}else{
				newIm.setDeleterId(user1.getId() + "");
			}
			this.commonManager.modifyEntity(newIm);
			outputData(0);
		}catch(Exception e){
			outputData(1);
		}
	}

	@Action("getImContent")//	 获取聊天的内容
	public void getImContent(){
		String imContent = "";// 聊天内容
		String imAboutTopic = "";// 关联的ID
		long userId = Long.parseLong(CookieUtil.getCookieValue(ServletActionContext.getRequest(), "cts_userid"));
		User user = this.commonManager.findEntityByPK(User.class, userId);
		if(uid == null){
			uid = 0l;
		}
		User sender = this.commonManager.findEntityByPK(User.class, uid);
		if(sender != null){
			imList = imManager.getNotReadChatByOneUser(user, sender);
			if(imList != null && imList.size() != 0){
				imManager.modifyIMsReadState(imList);
				for(IM im: imList){
					// ---------------
					if(im.getWorkId() != null){
						Work w = this.commonManager.findEntityByPK(Work.class, im.getWorkId());
						if(w != null){
							im.setSheetUrl("window.open('workDetail.action?id="+w.getId()+"')");
						}else{
							im.setSheetUrl("alert('该价格单已被删除！')");
						}
						imAboutTopic = "<a href=\"javascript:" + im.getSheetUrl() + "\">" + im.getMsgContent() + "</a>";
					}
					// --------------
					else{
						imContent += sender.getUserName() + "　" + TimeUtil.getFormatTimeString(im.getSendDate()) + "\r\n　　" + im.getMsgContent() + "\r\n";
					}
				}
			}
		}
		im = imManager.getNewChat(user, sender);
		if(im != null){
			imContent += "|" + im.getWorkId() + "|" +isUserOnline(sender.getId())+ "|" + imAboutTopic;
		}else{
			imContent = isUserOnline(sender.getId())+ "";
		}
		outputData(imContent);
	}
	
	private void outputData(Object obj){
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");

		try{
			response.getWriter().print(obj);
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
	public CommonManager getCommonManager() {
		return commonManager;
	}

	public void setCommonManager(CommonManager commonManager) {
		this.commonManager = commonManager;
	}

	public List<Map<User, Integer>> getDataList() {
		return dataList;
	}

	public void setDataList(List<Map<User, Integer>> dataList) {
		this.dataList = dataList;
	}

	public IM getIm() {
		return im;
	}

	public void setIm(IM im) {
		this.im = im;
	}

	public List<IM> getImList() {
		return imList;
	}

	public void setImList(List<IM> imList) {
		this.imList = imList;
	}

	public ImManager getImManager() {
		return imManager;
	}

	public void setImManager(ImManager imManager) {
		this.imManager = imManager;
	}

	public Map<User, Integer> getImMap() {
		return imMap;
	}

	public void setImMap(Map<User, Integer> imMap) {
		this.imMap = imMap;
	}

	public String getMsgContent() {
		return msgContent;
	}

	public void setMsgContent(String msgContent) {
		this.msgContent = msgContent;
	}

	public int getPageNumberIm() {
		return pageNumberIm;
	}

	public void setPageNumberIm(int pageNumberIm) {
		this.pageNumberIm = pageNumberIm;
	}

	public Page getPager() {
		return pager;
	}

	public void setPager(Page pager) {
		this.pager = pager;
	}

	public int getPageSizeIm() {
		return pageSizeIm;
	}

	public void setPageSizeIm(int pageSizeIm) {
		this.pageSizeIm = pageSizeIm;
	}

	public long getWorkId() {
		return workId;
	}

	public void setWorkId(long workId) {
		this.workId = workId;
	}

	public Long getUid() {
		return uid;
	}

	public void setUid(Long uid) {
		this.uid = uid;
	}
}
